
const canvasWatermark = (container = document.body, _option = {}) => {
  const params = Object.assign({
    width: '260px',
    height: '200px',
    opacity: '0.2',
    fontSize: '12px',
    zIndex: 20420,
    content: '水印'
  }, _option)
  const svgStr = `<svg xmlns="http://www.w3.org/2000/svg" width="${params.width}" height="${params.width}">
      <text x="50%" y="50%" dy="12px"
        text-anchor="middle"
        stroke="#999"
        stroke-width=".5"
        stroke-opacity="${params.opacity}"
        fill="none"
        transform="rotate(-30, 120 120)"
        style="font-size: ${params.fontSize};letter-spacing: 2px">
        ${params.content}
      </text>
    </svg>`
  const base64Url = `data:image/svg+xml;base64,${window.btoa(unescape(encodeURIComponent(svgStr)))}`
  const styleStr = `z-index: ${params.zIndex};position: fixed;pointer-events: none;height: 100%;width: 100%;top: 0px;left: 0px;background-image: url(${base64Url});background-repeat: repeat;background-position: 200px 20px, 0px 0px;
    `
  let watermarkDom = null
  const addWatermarkDiv = () => {
    const watermarkDiv = document.createElement('div')
    watermarkDiv.setAttribute('style', styleStr)
    watermarkDiv.classList.add('__wm')
    watermarkDom = watermarkDiv
    container.style.position = 'relative'
    container.insertBefore(watermarkDiv, container.firstChild)
  }

  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver
  let mObserver = null
  if (MutationObserver) {
    mObserver = new MutationObserver(() => {
      const __wm = document.querySelector('.__wm')
      // 只在__wm元素变动才重新调用 __canvasWM
      // 元素被删除
      if (!__wm) {
        mObserver.takeRecords()
        addWatermarkDiv()
        return
      }
      // 元素属性变动
      if (__wm.getAttribute('style') !== styleStr) {
        mObserver.takeRecords()
        __wm.setAttribute('style', styleStr)
      }
    })
    mObserver.observe(container, {
      // characterData: true,
      attributes: true, // 目标节点的属性节点(新增或删除了某个属性,以及某个属性的属性值发生了变化)
      subtree: true, // 观察目标节点的所有后代节点
      childList: true // 目标节点的子节点(新增 || 移除)
    })
  }

  return () => {
    mObserver && mObserver.disconnect()
    mObserver = null
    document.body.removeChild(watermarkDom)
    watermarkDom = null
  }
}

export {
  canvasWatermark
}
